package com.lu.manage.core.xss;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @program LuBoot
 * @description:
 * @author: zhanglu
 * @create: 2019-10-14 21:40:00
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String[] getParameterValues(String params) {
        String[] values = super.getParameterValues(params);
        if(values == null){
            return null;
        }
        int count = values.length;

        String[] encodedValues = new String[count];
        for(int i = 0; i < count; i++){
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }

    @Override
    public String getParameter(String param) {
        String value = super.getParameter(param);
        if(value == null){
            return null;
        }
        return cleanXSS(value);
    }

    @Override
    public String getHeader(String param) {
        String value = super.getHeader(param);
        if(value == null){
            return null;
        }
        return cleanXSS(value);
    }

    private String cleanXSS(String value) {

        //You'll need to remove the spaces from the html entities below

        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");

        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");

        value = value.replaceAll("'", "& #39;");

        value = value.replaceAll("eval\\((.*)\\)", "");

        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");

        value = value.replaceAll("script", "");

        return value;

    }
}
